package com.hqyj.controller;

import com.hqyj.pojo.UserInfo;
import com.hqyj.service.UserInfoService;
import com.hqyj.utile.SmsSend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

@Controller
@RequestMapping("/day02")
public class DayTwoController {
    @Autowired
    SmsSend smsSend;
    //注入service
    @Autowired
    UserInfoService userInfoService;
    //访问登录页页面
    @RequestMapping("/login")
    public String day02(Model map){

        return "/day02/login";
    }
    //访问主页面
    @RequestMapping("/index")
    public String index(){

        return "/day02/index";
    }
    //访问list页面
    @RequestMapping("/list")
    public String list(Model map){
        map.addAttribute("list",userInfoService.select());
        return "/day02/list";
    }
    //发送短信
    @RequestMapping("/sendSms")
    @ResponseBody
    public HashMap<String,Object> sendSms(String phone, HttpServletRequest request){
        HashMap<String,Object> map = new HashMap<String,Object>();
        Random rd = new Random();
        int code = rd.nextInt(1000);
        //发送短信
        String info = smsSend.send(phone,code+"");
        //判断是否成功
        if(info.equals("OK")){
            //存入session中
            request.getSession().setAttribute("smsCode",code);
            map.put("info","短信发送成功");
        }else{
            map.put("info","短信发送失败");
        }

        return map;
    }

    //手机短信登录
    @RequestMapping("/smsLogin")
    @ResponseBody
    public HashMap<String,Object> smsLogin(String tel,String code, HttpServletRequest request){
        HashMap<String,Object> map = new HashMap<String,Object>();
        String sessionCode = request.getSession().getAttribute("smsCode")+"";
        if(code.equals(sessionCode)){
            //根据电话去查询用户的名，并存入到session中
            request.getSession().setAttribute("user",tel);
            map.put("info","登录成功");
        }else{
            map.put("info","登录失败");
        }
        return map;
    }

}
